import FdContainerBaseComponent from '../../common/containerBase/containerBase';
import { TabPageProp } from '../property/tab-page-property-config';
import { FormPropertyChangeObject } from '../../../../entity/property-change-entity';
import { ElementPropertyConfig } from '@farris/ide-property-panel';
import { TabToolbarItemSchema, TabToolbarSchema } from '../schema/schema';
import { cloneDeep } from 'lodash-es';
import { DomService, RefreshFormService } from '@farris/designer-services';

export default class FdTabPageComponent extends FdContainerBaseComponent {

    constructor(component: any, options: any) {
        super(component, options);
        this.viewModelId = this.parent.viewModelId;
        this.componentId = this.parent.componentId;
    }

    /**
     * 组装属性面板配置数据
     */
    getPropertyConfig(): ElementPropertyConfig[] {
        const serviceHost = this.options && this.options.designerHost;
        const prop = new TabPageProp(serviceHost, this.viewModelId, this.componentId);
        const propertyConfig: ElementPropertyConfig[] = prop.getPropConfig(this.component);
        return propertyConfig;
    }

    attach(element: HTMLElement): Promise<any> {
        const superAttach: any = super.attach(element);
        this.element = element;

        // 删除标签页图标点击事件
        const removeButton = this.element.querySelector('[ref="removeTabPage"]');
        removeButton.addEventListener('click', () => {
            const tabPageTitle = removeButton.getAttribute('tabPageTitle') || '';
            const tabPageId = removeButton.getAttribute('tabPageId') || '';

            this.removeTabPage(tabPageTitle, tabPageId);
        });

        // 新增工具栏图标点击事件
        const addToolbarButton = this.element.querySelector('[ref="addToolbar"]');
        if (addToolbarButton) {
            addToolbarButton.addEventListener('click', () => {
                this.addToolbarForTabPage();
            });
        }

        this.setToolbarParentPathName();
        return superAttach;
    }

    private setToolbarParentPathName() {
        if (!this.component.toolbar || !this.component.toolbar.contents) {
            return;
        }
        const domService = this.options.designerHost.getService('DomService') as DomService;
        const toolbarBtns = this.component.toolbar.contents || [];
        toolbarBtns.forEach(button => {
            domService.controlBasicInfoMap.set(button.id, {
                showName: button.title,
                parentPathName: `${this.component.title} > ${button.title}`
            });
        });
    }

    triggerComponentClicked(e) {
        // 切换标签页时，清空上个标签页记录的滚动节点
        this.parent.scrollElementId = null;

        // 触发显示蓝色边框和按钮
        this.triggerComponentClick();

        // 切换到当前标签页的属性面板
        this.parent.emit('componentClicked', { e, componentInstance: this });
    }
    /**
     * 移除标签页
     * @param tabPageTitle 标签页的标题
     * @param tabPageId 标签页的标识
     */
    removeTabPage(tabPageTitle: string, tabPageId: string) {
        const msgService = this.options.designerHost.getService('MessagerService');
        if (!msgService || !msgService.question) {
            return;
        }
        msgService.question(`确定删除标签页【${tabPageTitle}】？`, () => {
            const contents = this.parent.component.contents;
            const index = contents.findIndex(content => content.id === this.component.id);
            contents.splice(index, 1);

            // 若删除的标签页为默认标签页，则需要重置默认标签页
            if (this.parent.component.selected === tabPageId) {
                this.parent.component.selected = contents.length ? contents[0].id : null;
            }
            // 删除后显示第一个标签页
            this.parent.component.currentTabPageInDesignerView = contents.length ? contents[0].id : null;

            // 调用子级组件的删除回调方法
            this.removeChildComponent(index);

            // 刷新页面，触发控件树更新
            const refreshFormService = this.options.designerHost.getService('RefreshFormService') as RefreshFormService;
            refreshFormService.refreshFormDesigner.next(this.parent.component.id);

            // 需要清除属性面板的数据
            this.parent.emit('clearPropertyPanel');

        });

    }

    /**
     * 调用标签页下子组件的[删除后事件]，主要用于删除ComponentRef关联的Component和ViewModel
     * @param index 当前标签页索引
     */
    removeChildComponent(index: number): void {
        // Tab上记录的所有的子组件，这里将所有TabPage的子组件放到一起了，所以需要再筛选一遍当前TabPage的子组件
        const childComponents = this.parent.tabPageComponents[index];
        if (childComponents) {
            childComponents.forEach(c => {
                if (c.onRemoveComponent) { c.onRemoveComponent(); }
            });
        }

    }
    /**
     * 属性变更后事件：默认监听样式类属性变更，并触发模板重绘
     * @param changeObject 变更集
     * @param propertyIDs 需要额外监听的属性ID列表
     */
    onPropertyChanged(changeObject: FormPropertyChangeObject): void {
        this.parent.onPropertyChanged(changeObject);
    }

    /**
     * 新增工具栏，用于标签页没有工具栏的场景
     */
    private addToolbarForTabPage() {
        const random = Math.random().toString().slice(2, 6);
        if (!this.component.toolbar || !this.component.toolbar.contents) {
            this.component.toolbar = cloneDeep(TabToolbarSchema);
            this.component.toolbar.id = 'tab-toolbar-' + random;
        }

        const newTabToolbarItem = cloneDeep(TabToolbarItemSchema);
        newTabToolbarItem.id = 'tab-toolbaritem-' + random;

        this.component.toolbar.contents.push(newTabToolbarItem);

        this.parent.redraw();
    }
}
